package cn.com.cetccst.appstore.ui.fragment;

import static cn.com.cetccst.appstore.ui.fragment.viewmodel.AppListViewModel.TYPE_STORE;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import cn.com.cetccst.appstore.BR;
import cn.com.cetccst.appstore.R;
import cn.com.cetccst.appstore.database.model.AppModel;
import cn.com.cetccst.appstore.databinding.FragmentAppListBinding;
import cn.com.cetccst.appstore.ui.activity.AppDetailActivity;
import cn.com.cetccst.appstore.ui.fragment.viewmodel.AppListViewModel;
import cn.com.cetccst.uicomponents.binding.app.DataBindingConfig;

public class AppListFragment extends BaseFragment<FragmentAppListBinding> {

    public static final String EXTRA_TYPE = "extra_type";
    public static final String EXTRA_CATEGORY_ID = "extra_category_id";
    private AppListViewModel viewModel;
    private AppListAdapter adapter;

    @Override
    protected void initViewModel() {
        viewModel = getFragmentScopeViewModel(AppListViewModel.class);
    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        adapter = new AppListAdapter(getContext(), item -> {
            Intent intent = new Intent(getContext(), AppDetailActivity.class);
            intent.putExtra(AppDetailActivity.EXTRA_APP_ID, item.getAppId());
            startActivity(intent);
        });

        return new DataBindingConfig(R.layout.fragment_app_list, BR.viewModel, viewModel)
                .addBindingParam(BR.adapter, adapter)
                .addBindingParam(BR.refreshListener, (SwipeRefreshLayout.OnRefreshListener) () -> viewModel.requestAppList(getContext()));
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (getArguments() != null) {
            viewModel.setPageType(getArguments().getInt(EXTRA_TYPE, TYPE_STORE));
            viewModel.setCategory(getArguments().getString(EXTRA_CATEGORY_ID));
        }
        viewModel.requestAppList(getContext());
    }

    @Override
    public void search(String key) {
        super.search(key);
        viewModel.searchKey.setValue(key);
        viewModel.requestAppList(getContext());
    }

    public interface OnFragmentInteractionListener {
        void onListFragmentInteraction(AppModel item);
    }

}
